using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using Portal.Core;

using Portal.Core.Web.UI;
using Portal.Data.Entity;

namespace Portal.Data.Webparts
{
    public class WebpartPageControl : WebControl
    {
        #region private member

        private DragDropProvider DragDrop = new DragDropProvider();

        #endregion

        #region properties

        public WebpartPage Info { get; set; }

        public PageViewMode ViewMode { get; set; }

        public WebLayout WebLayout { get; set; }

        public string Title { get; set; }

        #endregion

        #region Event-Handler

        protected override void OnInit(EventArgs e)
        {
            if (Lisence.IsExpired())
            {
                Page.Response.Redirect(CoreContext.basepath + "LicenseExpired.aspx");
            }
            base.OnInit(e);
            LoadPage();
        }

        private void LoadPage()
        {
            if (ViewMode == PageViewMode.Browse)
            {
                LoadLayout();
                IWebpartLoader loader = new BrowseModeWebpartLoader();
                loader.WebPage = Page;
                LoadModules(loader);
            }
            else
            {
                LoadLayout();
                DragDrop.SetLayout(WebLayout);
                IWebpartLoader loader = new DesignModeWebpartLoader();
                loader.WebPage = Page;
                LoadModules(loader);
            }
        }

        private void LoadLayout()
        {
            var layout = Info.Layout();
            if (layout != null)
            {
                WebLayout = Layout.LoadLayout(Page, layout.Path);
                Controls.Add(WebLayout);
            }
        }

        private void LoadModules(IWebpartLoader loader)
        {
            var parts = Webpart.FindByWebpartPage(Info.ID);

            //render
            for (int i = 0; i < parts.Count; i++)
            {
                var part = parts[i];
                PlaceHolder zone = WebLayout[part.Zone];
                if (zone != null)
                {
                    zone.Controls.Add(loader.Contain(part));
                }
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            DragDrop.Render(writer);
        }

        #endregion
    }
}